package com.jakewharton.rxbinding2.widget;

import com.jakewharton.rxbinding2.InitialValueObservable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import ohos.agp.components.Text;

final class TextObservable extends InitialValueObservable<CharSequence> {
  private final Text view;

  TextObservable(Text view) {
    this.view = view;
  }

  @Override
  protected void subscribeListener(Observer<? super CharSequence> observer) {
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);

    view.addTextObserver(listener);
//    view.addTextChangedListener(listener);
  }

  @Override protected CharSequence getInitialValue() {
    return view.getText();
  }

  final static class Listener extends MainThreadDisposable implements Text.TextObserver {
    private final Text view;
    private final Observer<? super CharSequence> observer;

    Listener(Text view, Observer<? super CharSequence> observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override
    protected void onDispose() {
      view.removeTextObserver(this);
    }

    @Override
    public void onTextUpdated(String text, int start, int before, int count) {
      if (!isDisposed()) {
        observer.onNext(text);
      }
    }
  }
}
